package com.zhudi.advice;


import com.zhudi.expection.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Modifier;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Objects;

import static com.zhudi.commen.ErrorCode.PARAMS_ERROR;

@Component
@Aspect
@Slf4j
public class MethodAdvice {

    @Pointcut("execution( * com.zhudi.controller.*.*(..))")
    private void servicePointCut(){}

    @AfterReturning(value = "servicePointCut()",returning = "serviceResult")
    public void after(JoinPoint joinPoint,Object serviceResult){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        log.info("---------------------------------------------------------------------------------");
        log.info("目标方法执行时间:"+LocalDateTime.now().format(formatter));
        log.info("目标方法所属类的简单类名:" +        joinPoint.getSignature().getDeclaringType().getSimpleName());
        log.info("目标方法所属类的类名:" + joinPoint.getSignature().getDeclaringTypeName());
        log.info("目标方法声明类型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
        log.info("目标方法名为:" + joinPoint.getSignature().getName());
        log.info("目标方法参数值集合："+ Arrays.asList(joinPoint.getArgs()));
        log.info("目标方法返回值为："+serviceResult.toString());
        //todo 修改为请求和结果分开，解决如果抛异常，无法正常记录请求的问题
        log.info("---------------------------------------------------------------------------------\n");
    }

    /**
     * 用于检查参数是否为空
     * @param joinPoint
     */
    @Before(value = "servicePointCut()")
    public void ParameterNullCheck(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (Objects.isNull(arg)){
                throw new BusinessException(PARAMS_ERROR);
            }
        }

    }


}
